<template>
  <van-list
    :error.sync="error"
    error-text="加载失败 请点击重试"
    v-model="loading"
    :finished="finished"
    finished-text="已显示全部评论"
    @load="onLoad"
  >
    <comment-item
      @re-comment="$emit('re-comment',$event)"
      v-for="(item,index) in list"
      :key="index"
      :data="item"
    ></comment-item>
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment.js'
import commentItem from '@/components/comment-item'
export default {
  created () {
    this.onLoad()
  },
  props: {
    needId: {
      type: [Number, Object, String],
      required: true
    },
    type: {
      required: true
    },
    list: {
      type: Array
    }
  },
  components: {
    commentItem
  },
  data () {
    return {
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false
    }
  },
  methods: {
    async  onLoad () {
      // 异步更新数据
      try {
        const { data: res } = await getComments({
          type: this.type,
          source: this.needId.toString(),
          offset: this.offset,
          limit: this.limit
        })
        this.list.push(...res.data.results)
        this.offset = res.data.last_id
        if (res.data.results.length === 0) {
          this.finished = true
        }
        console.log(res)
        this.$emit('comment', res.data)
      } catch (err) {
        this.error = true
      }
      this.loading = false
    }
  }
}
</script>

<style>
</style>
